Wait
Wait is a set of simple wrapper functions for delaying activity in JavaScript and CoffeeScript. (All code examples below are in CoffeeScript, but don't let that deter you if you love your curly braces.)
This is pure syntactic sugar, so if you're obsessed with performance über alles, move along.
Examples
wait 50, ->
# This callback will run in 50 milliseconds
The wait
function is simple setTimeout
with the arguments reversed, thus saving die-hard CoffeeScripters from the hell that is parentheses.
repeat 50, ->
# This callback will run every 50 milliseconds
Same as wait
, but for setInterval
instead of setTimeout
.
doAndRepeat 50, ->
# This callback will run immediately, and be run again every 50 ms
Pretty self-explanatory.
waitUntil checkCondition, ->
# This callback will run when `checkCondition` returns a true-ish value
This is as close as you're going to get to Thread.sleep
in JavaScript. Internally, waitUntil
uses setInterval
to check the given condition every 100ms by default; you can provide a different interval as the second argument, e.g.
waitUntil checkCondition, 50, ->
# This callback will run when `checkCondition` returns a true-ish value
Note that the condition isn't checked until after the first interval has elapsed.
Oh, and the return value for all of these is the handle returned by setTimeout
or setInterval
, so you can use clearTimeout
or clearInterval
at your discretion.
Installation
Wait is compatible with Node.js and all major web browsers. For node, use npm:
npm install wait
and then require
the library like so (using the magic of CoffeeScript pattern-matching):
{wait, repeat, doAndRepeat, waitUntil} = require 'wait'
If you're in browserland, just add wait.js
from the lib
dir to your project.